const Controller = require('egg').Controller;

module.exports = class BaseController extends Controller {
  // 封装公用 分页查询方法
  async getPager({modelName = '', fields = [], populateFields = []}){
    const {ctx} = this;
    let {pageNum=1, pageSize=5, keyword} = ctx.query;
    pageNum = isNaN(pageNum)? 1: parseInt(pageNum);
    pageSize = isNaN(pageSize)? 5: parseInt(pageSize);
    let query = {};
    if (keyword && fields.length > 0) {
      // 关键字在 title 和content里面进行匹配
      query['$or'] = fields.map(field => { return {[field]: new RegExp(keyword)}})      
    }
    // 返回总条数 
    let total = await ctx.model[modelName].count(query);

    let cursor = ctx.model[modelName]
                    .find(query)
                    .skip((pageNum - 1) * pageSize)
                    .limit(pageSize);
    populateFields.forEach(field => {
      cursor = cursor.populate(field);
    })          
    let items = await cursor;
    
    this.success({
      items,
      total,
      pageNum,
      pageSize,
      pageCount: Math.ceil(total/pageSize)
    })
  }

  success(data) {
    this.ctx.body = {
      code: 0,
      data
    }
  }
  error(error){
    this.ctx.body = {
      code: 1,
      error
    }
  }

  get user() {
    return this.ctx.session.user;
  }
  
}

